package cn.gary.oaserver.service.impl;

import cn.gary.oaserver.entity.TAdmin;
import cn.gary.oaserver.entity.TRole;
import cn.gary.oaserver.mapper.TAdminMapper;
import cn.gary.oaserver.mapper.TRoleMapper;
import cn.gary.oaserver.params.PageParams;
import cn.gary.oaserver.service.ITAdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gary
 * @since 2024-03-15
 */
@Service
public class TAdminServiceImpl extends ServiceImpl<TAdminMapper, TAdmin> implements ITAdminService {

    @Autowired
    TRoleMapper roleMapper;

    @Override
    public TAdmin getAdminByUsername(String username) {
        QueryWrapper<TAdmin> qw = new QueryWrapper<> ( );
        qw.eq ( "username", username );
        return baseMapper.selectOne ( qw );
    }

    @Override
    public IPage<TAdmin> getAdminListByQuery(PageParams pageParams, String query) {
        Page<TAdmin> page = new Page<> ( pageParams.getPageIndex ( ), pageParams.getPageSize ( ) );
        QueryWrapper<TAdmin> qw = new QueryWrapper<> ( );
        qw.like ( "name", query ).or ( ).like ( "phone", query );
        if (pageParams.getSort ( ) != null) {
            if (pageParams.getSort ( ).startsWith ( "asc" )) {
                qw.orderByAsc ( true, pageParams.getSort ( ).substring ( pageParams.getSort ( ).indexOf ( "_" ) + 1 ) );
            } else {
                qw.orderByDesc ( true, pageParams.getSort ( ).substring ( pageParams.getSort ( ).indexOf ( "_" ) + 1 ) );
            }
        }
        IPage<TAdmin> tAdminIPage = baseMapper.selectPage ( page, qw );
        tAdminIPage.getRecords ( ).stream ( ).map ( admin -> {
            admin.setRoles ( findRolesAndMenusByAdminId ( admin.getId() ) );
            return admin;
        } ).collect(Collectors.toList());
        return tAdminIPage;
    }

    @Override
    public List<TRole> findRolesAndMenusByAdminId(Integer adminId) {
        List<TRole> collect = baseMapper.findRolesByAdminId ( adminId ).stream ( ).map ( role -> {
            role.setChildren ( roleMapper.findMenuByRoleId ( role.getId ( ) ) );
            return role;
        } ).collect ( Collectors.toList ( ) );
        return collect;
    }

    @Override
    public List<String> getMenuUrlByAdminId(Integer id) {
        return baseMapper.getMenuUrlByAdminId(id);
    }
}
